//
//  MyLocation.swift
//  ShareUmbrella
//
//  Created by niupark on 2017/9/11.
//  Copyright © 2017年 尧尚信息科技. All rights reserved.
//

import UIKit
import RxSwift
import YSKit

let Location = MyLocation.sharedInstance

//地理编码信息
struct LocationReGeocode {
    var city: String = "" //城市信息
}

class MyLocation:NSObject, AMapLocationManagerDelegate{
    static let sharedInstance = MyLocation()
    //最新的位置信息
    public let location: Variable<CLLocation?> = Variable(nil)
    public let locationReGeocode: Variable<LocationReGeocode?> = Variable(nil)
    private let locationManager = AMapLocationManager()
    private var timer:Timer?

    private override init(){
        super.init()
        self.locationManager.delegate = self
        self.locationManager.distanceFilter = 50
        self.locationManager.locatingWithReGeocode = true
        
        //监听用户登录操作
        _  = Auth.isLogin.asObservable().takeUntil(self.rx.deallocated).subscribe(onNext: { [weak self] (isLogin) in
            guard let `self` = self else {
                return
            }
            if isLogin {
                self.startup()
                self.startUploadLocation()
            }else {
                self.stopUploadLocation()
                self.stop()
            }
            
        })
        

    }
    
    private func startUploadLocation() {
        guard let t = self.timer else {
            self.timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true, block: { (timer) in
                
                guard let location = self.location.value else {
                    return
                }
                
                //上报位置信息
                _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(UserAPI.updateLocation(token: Auth.token, latitude: location.coordinate.latitude, longitude: location.coordinate.longitude))).subscribe(onNext: { (data) in
                    //
                    
                    print("位置上报--->成功")
                }, onError: {(ErrorType) in
                    
                    print("位置上报-->失败")
                    
                })
            })
            self.timer?.fire()
            return
        }
    }
    
    private func  stopUploadLocation() {
        guard let t = self.timer else {
            return
        }
        
        t.invalidate()
        self.timer = nil
    }
    
    public func startup() {
        //iOS 9（不包含iOS 9） 之前设置允许后台定位参数，保持不会被系统挂起
        locationManager.pausesLocationUpdatesAutomatically = true
        
        //iOS 9（包含iOS 9）之后新特性：将允许出现这种场景，同一app中多个locationmanager：一些只能在前台定位，另一些可在后台定位，并可随时禁止其后台定位。
        if UIDevice.current.systemVersion._bridgeToObjectiveC().doubleValue >= 9.0 {
            locationManager.pausesLocationUpdatesAutomatically = true
        }
        
        //开始持续定位
        locationManager.startUpdatingLocation()
    }
    public func stop() {
        locationManager.stopUpdatingLocation()
    }
    
    func amapLocationManager(_ manager: AMapLocationManager!, didUpdate location: CLLocation!, reGeocode: AMapLocationReGeocode?) {
        print("location:{lat:\(location.coordinate.latitude); lon:\(location.coordinate.longitude); accuracy:\(location.horizontalAccuracy)};")
        self.location.value = location
        if let reg = reGeocode {
            
            var g = LocationReGeocode()
//            g.city = reg.city
            self.locationReGeocode.value = g
        }else {
            
            CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (placemarks, error) in
                
                guard let p = placemarks, p.count > 0, error == nil else {
                    print("反地理编码失败。。。")
                    return
                }
                
                if let city = p[0].locality {
                    var g = LocationReGeocode()
                    g.city = city
                    self.locationReGeocode.value = g
                    
                }
                
                
            })
            
        }
    }
    
    
}
